import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from 'vuex-persistedstate'
import axios from "axios";
Vue.use(Vuex);

export default
    new Vuex.Store({
        state: {
            showPage: 0,
            shoppingCart: [],
            shoppingCartCount:0,
        },
        mutations: {
            setShowPage: function (state, val) {
                state.showPage = val;
            },
            SET_SHOPPING_CART(state, payload) {
                state.shoppingCart = Array.isArray(payload) ? payload : [];
            },
            CLEAR_SHOPPING_CART(state){
                state.shoppingCart=[];
            },
        },
        actions: {
            changShowPage: function (context, val) {
                context.commit('setShowPage', val);
            },
            setShoppingCart({ commit }, payload) {
                commit('SET_SHOPPING_CART', payload)
            },
            async fetchCart({ commit }) {
                try {
                    const response = await axios.get('/api/shoppingCart/getShoppingCart', {
                        headers: {
                            Authorization: `Bearer ${localStorage.getItem('token')}`
                        }
                    });

                    if (response.data.code === 200) {
                        commit('SET_SHOPPING_CART', response.data.list);
                    }
                } catch (error) {
                    console.error('获取购物车失败:', error);
                    commit('SET_SHOPPING_CART', []);
                }
            },
            clearShoppingCart({commit}){
                commit('CLEAR_SHOPPING_CART');
            }
        },
        getters: {
            getShowPage: state => state.showPage,
            getShoppingCart: state => state.shoppingCart,
            getCartTotal: state => {
                return state.shoppingCart.reduce((total, item) => {
                    return total + (item.cost*item.quantity || 0);
                }, 0);
            },
            getCartItemCount: state => {
                return state.shoppingCart.reduce((count) => {
                    return count + 1;
                }, 0);
            }
        },
        plugins: [createPersistedState()]
    })